//市场部周计划
Ext.namespace("AuditPlan");

AuditPlan.WeeklyAudit = function(p) {
	this.winParent = p;
	this.winTasks = null;
	this.winMsg=null;
	this.loadMask = null;
	this.current=null;
	thiz=this;
	this.planId =null;
	this.createId =null;
	this.remind=null;
	this.startDate=null;
	this.endDate=null;
	
	this.txtItem = new Ext.form.TextField({
		fieldLabel: '任务名称',
		name:'itemTitle',
		allowBlank: false,
		width: 340
	});
	this.txtContent = new Ext.form.TextArea({
		fieldLabel: '内容描述',
		name:'itemContent',
		allowBlank: false,
		width: 570,
		height: 45
	});
	this.txtOther = new Ext.form.TextArea({
		fieldLabel: '重点、难点及需协调事宜',
		name:'itemOther',
		height: 35,
		width: 580
	});
	this.txtRemark = new Ext.form.TextArea({
		fieldLabel: '备注',
		name:'itemRemark',
		height: 24,
		width: 580
	});
	
	this.txtNation = new Ext.form.TextArea({
		fieldLabel: '审核意见',
		name:'itemNation',
		width: 570,
		height: 45
	});	
	this.storeSource  = new Ext.data.ArrayStore({
        	fields: ['value', 'name'],
        	data: OMS.TASKORIGINVALUE
    });
    this.storeType  = new Ext.data.ArrayStore({
        	fields: ['value', 'name'],
        	data: OMS.PLANCATEGORY2
    });
    this.storeSend  = new Ext.data.ArrayStore({
        	fields: ['value', 'name'],
        	data: [[0, '本周新增'], [1, '上周转入']]
    });
	this.renderSource = function(value){
		return OMS.TASKORIGIN[value];
	};
	this.renderSend = function(value){
		return OMS.PLAN_SEND[value];
	};
	this.renderStatus = function(value){
		return OMS.TASKSEXESTATUS[value];
	};	
	this.renderCategory = function(value){
		return OMS.PLANCATEGORY[value];
	};
	this.renderTitle=function(value){
		return Ext.util.Format.ellipsis(value,10,'...');
	}
	this.renderNation=function(value){
		return Ext.util.Format.ellipsis(value,12,'...');
	}
	this.renderContent=function(value){
		return Ext.util.Format.ellipsis(value,16,'...');
	}
	this.cmbType = new Ext.form.ComboBox({
		width: 120,
		store: this.storeType,
		fieldLabel: '任务类别',
		name:'itemCategory',
        valueField: 'value',
        displayField: 'name',
        editable: false,
        allowBlank: false,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus: true
	});
	this.cmbSend = new Ext.form.ComboBox({
		width: 120,
		store: this.storeSend,
		fieldLabel: '任务性质',
		name:'sendFlag',
        valueField: 'value',
        displayField: 'name',
        value:'0',
        editable: false,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus: true
	});
	this.cmbSource = new Ext.form.ComboBox({
		width: 120,
		fieldLabel: '任务来源',
		name:'workSource',
		store: this.storeSource,
        valueField: 'value',
        displayField: 'name',
        editable: false,
        allowBlank: false,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus: true
	});
   this.dtPlanWork = new Ext.form.Hidden({name:'planWork'});
    this.dtPlanFinish = new Ext.form.DateField({
    	width: 120,
    	fieldLabel: '完成时间',
    	name:'planFinish',
		format: 'Y-m-d'
	});
    this.btnUpdate = new Ext.Button({
    	text: '修改',
		iconCls: 'icon-update',
		scope: this,
		handler: this.onUpdate
    });
    this.btnNew = new Ext.Button({
    	text: '添加',
    	iconCls: 'icon-new',
    	scope: this,
    	handler: this.onNew
    });
    this.btnReset = new Ext.Button({
    	text: '修复',
    	iconCls: 'icon-reset',
    	scope: this,
    	handler: this.resetForm
    });
    this.btnAddTask = new Ext.Button({
    	text: '添加在执行中任务',
    	iconCls: 'icon-new',
    	scope: this,
    	handler: this.onAddTask
    });
    this.btnRemove = new Ext.Button({
    	text: '删除',
    	iconCls: 'icon-remove',
    	scope: this,
    	handler: this.onRemove
    });
    this.files=new Ext.Container({ layout: 'column', border: false, defaults: {layout: 'form', border: false},
	        	items: []
	    });
	this.form = new Ext.FormPanel({
		region: 'north',
        bodyStyle: 'padding: 5px 5px 0',
        height: 160,
        labelWidth: 70,
        labelAlign: 'right',
        items: [ { layout: 'column', border: false, defaults: {layout: 'form', border: false},
	        	items: [ { columnWidth: .33, items: [this.cmbSource] },
	        	         { columnWidth: .66, items: [this.txtItem]} ]
	    },{ layout: 'column', border: false, defaults: {layout: 'form', border: false},
	        	items: [ { columnWidth: .33, items: [this.cmbType]},
	        	         { columnWidth: .33, items: [this.dtPlanFinish]},
     	            	 { columnWidth: .33, items: [this.cmbSend] } ]
	    }, this.txtContent, this.txtNation,this.dtPlanWork,
	    	new Ext.form.Hidden({name:'itemId'}),
	    	new Ext.form.Hidden({name:'taskStatus'}),
	    	new Ext.form.Hidden({name:'taskId'}),this.files]
    });
	
	this.storeItems = new Ext.data.JsonStore({
	    url: Utils.formatURL('../myplan/listItems.form?&timesnap=' + Date.parse(new Date())),
	    root: 'result',
	    fields: ['itemId','taskId','taskStatus','itemCategory','itemTitle','itemOther','itemNation','itemRemark','workSource','itemContent','planWork','planFinish','sendFlag']
	});
	
	this.column = [
		  {header: '明细编号',  align: 'center', width: 20,hidden:true, dataIndex: 'itemId'},
		  {header: '任务编号',  align: 'center', width: 20,hidden:true, dataIndex: 'taskId'}, 	      
 	      {header: '任务来源',  align: 'center', width: 35, dataIndex: 'workSource',renderer:this.renderSource},
 	      {header: '任务名称',  align: 'left', width: 50,dataIndex: 'itemTitle',renderer:this.renderTitle}, 
 	      {header: '任务类别',  align: 'center', width: 30, dataIndex: 'itemCategory',renderer:this.renderCategory},        
 	      {header: '内容描述',  align: 'left', dataIndex: 'itemContent',renderer:this.renderContent},
 	      {header: '重点、难点及需协调事宜', width: 40,hidden:true, align: 'left', dataIndex: 'itemOther'},
 	      {header: '备注',  align: 'left',width: 40,hidden:true, dataIndex: 'itemRemark'},
 	      {header: '审核意见',  align: 'left', width: 80,dataIndex: 'itemNation',renderer:this.renderNation},
 	      {header: '开始时间',  align: 'center',hidden:true, width: 35, dataIndex: 'planWork'},
 	      {header: '完成时间',  align: 'center', width: 35,dataIndex: 'planFinish'},
 	      {header: '任务性质',  align: 'center', width: 30,dataIndex: 'sendFlag',renderer:this.renderSend},
 	      {header: '任务状态',  align: 'center', width: 25,hidden:true,dataIndex: 'taskStatus',renderer:this.renderStatus}
 	];
	
	this.grid = new Ext.grid.GridPanel({
		store: this.storeItems,
        region: 'center',
        tbar: {items: [this.btnUpdate, this.btnNew,this.btnReset, this.btnRemove]},
        cm: new Ext.grid.ColumnModel(this.column),
        sm: new Ext.grid.RowSelectionModel({singleSelect:false}),
        viewConfig: { forceFit: true },
        scope:this,
        listeners:{
      		  rowdblclick : function( g, index,e){      		  	
    			var rec = g.store.getAt(index);
    			this.scope.form.getForm().loadRecord(rec);
    			this.scope.current=rec;
			}
       }
	});
	
	AuditPlan.WeeklyAudit.superclass.constructor.call(this, {
		layout: 'border',
		title: '计划审核',
        width: 700,
        height: 420,
        resizable: false,
        modal: true,
        autoScroll: true,
        closeAction: 'hide',
        items: [this.form, this.grid],
		buttons:[{
            text: '提交',
            cls: 'x-btn-text-icon btn-save',
            handler: this.onSavePlan,
            scope: this
        }, {
            text: '关闭',
            cls: 'x-btn-text-icon btn-cancel',
            handler: this.hide.createDelegate(this, [])
        }]
    });
};
Ext.extend(AuditPlan.WeeklyAudit, Ext.Window,{
	resetForm:function(){
		this.form.getForm().reset();
		this.dtPlanWork.setValue(this.startDate);
		this.dtPlanFinish.setValue(this.endDate);
	},
	initWin:function(data){
		this.planId=data.planId;
		this.createId=data.createId;
		this.startDate=data.startDate;
		this.endDate=data.endDate;
		this.resetForm();
		/*
		this.files.removeAll(true);
		var conn = new Ext.data.Connection({
			url:'../myplan/searchUpLoadFiles.form?timesnap=' + Date.parse(new Date()),
			method:'post'
		})
		Utils.request(conn,{
			params:{planId:data.planId},
			scope:this,
			success:function(data){
				var files=data.result;
				for(var i=0;i<files.length;i++){
					this.scope.addFile(files[i]);
				}
				this.scope.form.doLayout();
			}
		});	*/	
		
		this.grid.store.load({
			params:{planId:data.planId}
		});	
	},
	addFile:function(o){
		var href='../myplan/downloadFile.form?fileId='+o.ACCESSORY_ID+'&timesnap=' + Date.parse(new Date());
		var lbLink=new Ext.form.Label({
			html:'<a href="'+href+'">'+o.ACCESSORY_NAME+'</>',
			width:120
		});	    	
		this.files.add(lbLink);	    
	},	
	onAddTask: function(btn, event) {
		if (this.winTasks == null) {
			this.winTasks = new MyPlan.AddTask(this);
		}
		this.winTasks.initWin();
		this.winTasks.show();
	},
	onNew: function(btn, event) {
		if (!this.form.getForm().isValid()){
			Utils.warn2('请输入相关信息再添加！',200);
			return;
		}
		var data=this.form.getForm().getFieldValues();
		
		//Utils.formatDate(data,'planWork');
		Utils.formatDate(data,'planFinish');
		//alert(Ext.util.JSON.encode(data));
		if(this.checkDate(data,this.startDate,this.endDate)) return;
		this.resetForm();		
		var rec = new this.grid.store.recordType(data);
        this.grid.store.insert(0, rec);
	},
	checkDate:function(data,startDate,endDate){
		/*if(data['planWork']>data['planFinish']){
			Utils.warn2('计划实施时间不应大于计划完成时间！',180);
			return true;
		}else if(data['planWork']<startDate){
			Utils.warn2('计划实施时间不应小于计划周期开始时间！',180);
			return true;
		}else */if(data['planFinish']>endDate){
			Utils.warn2('计划完成时间不应大于计划周期截至时间！',180);
			return true;
		}
		return false;
	},
	onRemove:function(btn,event){		
		var record = this.grid.getSelectionModel().getSelected();
		if(!record){
			Utils.warn2('请选择一条记录！',180);
			return false;
		}
		if(record.itemId!=null&&record.itemId!='undefined'
				&&record.taskId!=null&&record.taskId!='undefined'){
			Utils.warn2('有对应任务，不允许删除！',180);
			return false;
		}        
        scope=this;      
        Utils.confirm2({msg:"删除后将不可恢复，您确实要删除吗？",
        	width:220,
        	fn:function(){
		        	scope.storeItems.remove(record);
		       }
	    });
	},
	onUpdate: function(btn, event) {
		if(this.current==null){
			Utils.warn2('请选选择一条子计划！',180);
			return false;
		}		
		var data=this.form.getForm().getFieldValues();
		//对有任务ID只允许更新审核意见
		if(data['taskId']){
			var record=this.current; 
			record.set(['itemNation'],data['itemNation']);
			this.current=null;
			this.resetForm();
			return;
		}
		if (!this.form.getForm().isValid()){
			Utils.warn2('请输入相关信息再添加！',180);
			return;
		}
		//Utils.formatDate(data,'planWork');
		Utils.formatDate(data,'planFinish');		
		if(this.checkDate(data,this.startDate,this.endDate))
			return;
		var record=this.current; 
		this.current=null;
		this.resetForm();
		//alert(Ext.util.JSON.encode(data));
		for(var id in record.data){
			record.set([id],data[id]);
		}
	},
	/**
	 * 保存
	 */
	onSavePlan: function(btn, event){
		scope=this;
		if(this.winMsg==null)			
			this.winMsg=new Message.Msg(function(){
				scope.remind=scope.winMsg.txtRemind;	
				scope.savePlan();
			},'审核后就不可修改，你确实要保存吗？');
		this.winMsg.show();
	},
	savePlan: function(btn, event){			
		var conn = new Ext.data.Connection({
  			url:'../auditplan/auditPlan.form?timesnap=' + Date.parse(new Date()),
  			method:'post'
  		})
  		var param={planId:this.planId,createId:this.createId,remind:this.remind};
  		var count=this.storeItems.getCount();
  		var selModel=this.grid.getSelectionModel();
  		for(var i=0 ;i<count;i++){
			var data = this.storeItems.getAt(i).data;
			param['grid_'+i]=Ext.util.JSON.encode(data);
		};
		//alert(Ext.util.JSON.encode(param));		
		Utils.request(conn,{
  			params:param,
  			scope:this,
  			success:function(data){
  				Utils.info2();
				this.scope.hide();
				this.scope.winParent.store.reload();
  			}
  		});  		
	}
});